package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.jxc.dao.DamageListDao;
import com.atguigu.jxc.dao.DamageListGoodsDao;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.entity.User;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Gavin
 * @Date: 9/11/2023 9:59 PM
 */
@Service
public class DamageListService {
    @Autowired
    DamageListDao damageListDao;
    @Autowired
    DamageListGoodsDao damageListGoodsDao;
    public void save(HttpSession session, DamageList damageList, String damageListGoodsStr) {
        //1.查询获取用户的userId
        User user = (User)session.getAttribute("currentUser");
        Integer userId = user.getUserId();

        //2.保存damageList对象
        damageList.setUserId(userId);
        damageListDao.save(damageList);

        //3.保存damageListGoods对象(里面需要保存damageList的id)
        List<DamageListGoods> damageListGoods = JSON.parseArray(damageListGoodsStr, DamageListGoods.class);
        if(!CollectionUtils.isEmpty(damageListGoods)){
            //判断下不为空的时候再进行下一步的操作
            //遍历循环将对应的保存的商品保存到damageListGoods表里面
            damageListGoods.forEach(damageListGood -> {
                /* DamageListGoods damageListGoods = new DamageListGoods();
                BeanUtils.copyProperties(good,damageListGoods); */
                damageListGood.setDamageListId(damageList.getDamageListId());
                //将damageListGoods保存到数据库里面
                damageListGoodsDao.save(damageListGood);
            });
        }
    }

    public Map<String, Object> queryByTimeSection(String sTime, String eTime) {
        List<DamageList> damageLists = damageListDao.queryByTimeSection(sTime,eTime);
        Map<String,Object> map = new HashMap<>();
        map.put("rows",damageLists);
        return map;
    }

    public Map<String, Object> queryDamageListGoods(Integer damageListId) {
        List<DamageListGoods> damageListGoods = damageListGoodsDao.queryDamageListGoods(damageListId);
        Map<String,Object> map = new HashMap<>();
        map.put("rows",damageListGoods);
        return map;
    }
}
